import 'package:flutter/material.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/common/su_dialog.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:love_app/service/setting_info_api.dart';
import 'package:provider/provider.dart';

class SettingMyName extends StatefulWidget {
  final String myName;

  const SettingMyName({Key key, this.myName}) : super(key: key);

  @override
  _SettingMyNameState createState() => _SettingMyNameState();
}

class _SettingMyNameState extends State<SettingMyName> {
  ShareProvider _shareProvider;
  TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
    _controller.text = _shareProvider.nickname;
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Su().appBar(
        "我的昵称",
        colors: _shareProvider.themeColor,
        actionText: "保存",
        onActionClick: _settingUserName,
      ),
      resizeToAvoidBottomInset: false,
      body: _body(),
    );
  }

  // 页面
  Widget _body() {
    return Container(
      child: TextField(
        controller: _controller,
        maxLength: 12,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.all(20.0),
        ),
      ),
    );
  }

  Future<void> _settingUserName() async {
    String newName = _controller.text;
    if (newName.length > 0) {
      bool success =
          await SeetingInfoApi().settingUserName(_shareProvider.token, newName);
      if (success == true) {
        SuDialog.showToast("修改成功");
        _shareProvider.nickname = newName;
      }
      Navigator.pop(context);
      return SuDialog.showToast("修改失败");
    }else{
      SuDialog.showToast("名字不能为空");
    }
  }
}
